package com.example.sax;

import android.app.Person;
import android.text.TextUtils;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;

public class Myhandler extends DefaultHandler
{
    private List<Bean> mBeanList;
    private Bean person;
    private String mTag;

    public List<Bean> getmBeanList() {
        return mBeanList;
    }

    //文档解析开始
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        mBeanList = new ArrayList<>();
    }

    //文档解析结束
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
    }

    //标签开始
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);

        //扫描到开始标签<person>时，创建List元素，并获取属性
        if (localName.equals("person"))
        {
            person = new Bean();

            person.setId(attributes.getValue("id"));
        }
        //通过成员变量mTag
        mTag = localName;
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);

        if (localName.equals("person"))
        {
            mBeanList.add(person);
            //由于列表中多条数据结构相同，所以结束一条person数据后，需要将person对象制空
            person = null;
        }
        //因为有多个标签需要环迅标签名，  会被重新赋值，所以
        mTag = null;
    }

    //获取数据
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);

        //由于标签科涅能够为null，故判空
        if (!TextUtils.isEmpty(mTag))
        {
            switch (mTag)
            {
                case "name":
                    person.setName(new String(ch,start,length));
                    break;

                case "age":
                    person.setAge(new String(ch,start,length));
                    break;
            }
        }
    }
}
